package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.ManagerConstants;
import com.powernode.entity.SysRole;
import com.powernode.entity.SysRoleMenu;
import com.powernode.mapper.SysRoleMenuMapper;
import com.powernode.service.SysRoleMenuService;
import com.powernode.service.SysRoleService;
import com.powernode.mapper.SysRoleMapper;
import com.powernode.util.AuthUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author yanju
* &#064;description  针对表【sys_role(角色)】的数据库操作Service实现
* &#064;createDate  2024-11-01 16:01:33
 */
@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.SysRoleServiceImpl")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService{

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 查询系统所有角色(全量查询)
     * 全量查询是需要将数据存放到缓存里
     */
    @Cacheable(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    @Override
    public List<SysRole> querySysRoleList() {
        return sysRoleMapper.selectList(new LambdaQueryWrapper<SysRole>()
                .orderByDesc(SysRole::getCreateTime));
    }

    /**
     * 新增角色
     * @param sysRole 角色信息
     * @return 是否新增成功 true：成功
     */
    @Override
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)//清除缓存
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSysRole(SysRole sysRole) {
        //1.新增角色
        sysRole.setCreateTime(new Date());
        sysRole.setCreateUserId(AuthUtils.getLoginUserId());
        int count = sysRoleMapper.insert(sysRole);
        if (count > 0){
            //2.开始新增角色与权限关系
            //2.1.获取角色id
            Long roleId = sysRole.getRoleId();
            //2.2.获取权限id集合
            List<Long> menuIdList = sysRole.getMenuIdList();

            //2.2.先创建集合，避免循环操作数据库
            List<SysRoleMenu> list = new ArrayList<>();


            if (CollectionUtil.isNotEmpty(menuIdList)){
                //2.3.循环遍历权限集合
                menuIdList.forEach(menuId -> {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenu.setRoleId(roleId);
                    list.add(sysRoleMenu);
                });
                sysRoleMenuService.saveBatch(list);
            }
        }
        return count > 0;
    }


    /**
     * 根据标识查询角色详情
     * @param roleId 角色id
     * @return 角色信息
     */
    @Override
    public SysRole querySysRoleInfoByRoleId(Long roleId) {
        SysRole sysRole = sysRoleMapper.selectById(roleId);
        //根据角色标识查角色与权限关系id集合
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId));

        //判断是否有值
        if (!sysRoleMenuList.isEmpty()){
            //从关系集合中获取权限id集合
            List<Long> menuIdList = sysRoleMenuList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            sysRole.setMenuIdList(menuIdList);
        }

        return sysRole;
    }

    /**
     * 修改角色信息
     * @param sysRole 角色信息
     * @return 是否修改成功 true：修改成功
     */
    @Override
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)//清除缓存
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifySysRole(SysRole sysRole) {

        //1.获取角色id
        Long roleId = sysRole.getRoleId();
        //2.删除角色原有权限集合
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId,roleId));

        //3.获取角色对应权限id集合
        List<Long> menuIdList = sysRole.getMenuIdList();
        //创建角色权限关系集合：避免循环操作数据库
        List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
        //4.判断是否有值
        if (!menuIdList.isEmpty()){
            //4.1.有值，遍历权限集合
            for (Long menuId : menuIdList) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenuList.add(sysRoleMenu);
            }
            //4.2.写入数据库(角色权限关系)
            sysRoleMenuService.saveBatch(sysRoleMenuList);
        }

        //5.更改角色信息
        return sysRoleMapper.updateById(sysRole) > 0;
    }

    /**
     * 批量/单个删除角色
     * @param roleIdList 角色id集合
     * @return 是否删除成功 true 删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(ManagerConstants.SYS_ALL_ROLE_KEY)//删除缓存
    public Boolean removeSysRoleListByIds(List<Long> roleIdList) {
        //删除角色权限关系
        sysRoleMenuMapper.deleteBatchIds(roleIdList);
//        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
//                .in(SysRoleMenu::getRoleId,roleIdList));

        //删除角色
        return sysRoleMapper.deleteBatchIds(roleIdList) == roleIdList.size();
    }
}




